console.log("初始化页面")
console.log(`Chrome (v${electron.chrome_verison()})`);
console.log(`Node.js (v${electron.node_verison()})`);
console.log(`Electron (v${electron.electron_verison()})`);

const menu_flod_config = {
    button_class: ".dnfapp-menu .dnfapp-menu-title .fold-button",
    button_fold: true, //初始时为展开状态

    //class组1, fold为true时 添加unfold
    group_class1: [
        ".dnfapp-menu",
        ".dnfapp-menu .dnfapp-menu-search",
        ".dnfapp-menu .title1",
        ".dnfapp-menu .title2",
    ],

    //class组1, fold为true时添加 fold
    group_class2: [
        ".dnfapp-container"
    ],
}

const sql = electron.JDBC().sqlite

//菜单折叠展开
const checkFold = () => {
    let flodButton = document.querySelector(menu_flod_config.button_class);
    flodButton.addEventListener("click", function () {
        if (menu_flod_config.button_fold) {
            menu_flod_config.button_fold = !menu_flod_config.button_fold; //=>false
            menu_flod_config.group_class1.forEach((e) => {
                let element = document.querySelector(e);
                element.className = element.className.replace("unfold", "fold")
            });

            menu_flod_config.group_class2.forEach((e) => {
                let element = document.querySelector(e);
                element.className = element.className.replace("fold", "unfold")
            });
        } else {
            menu_flod_config.button_fold = !menu_flod_config.button_fold; //=>true
            menu_flod_config.group_class1.forEach((e) => {
                let element = document.querySelector(e);
                element.className = element.className.replace("fold", "unfold")
            });

            menu_flod_config.group_class2.forEach((e) => {
                let element = document.querySelector(e);
                element.className = element.className.replace("unfold", "fold")
            });
        }
    })
}

const checkSearchListener = () => {
    let searchInput = document.querySelector(".dnfapp-menu .dnfapp-menu-search .search-input");
    let listContainer = document.querySelector("#dnfapp-menu-list");
    let list = [].slice.call(listContainer.childNodes).filter(e => e.nodeType == 1);
    let search = searchInput.value;

    list.forEach(ls => {
        let name = ls.getAttribute("name");
        if (name.indexOf(search) == -1) {
            //不包含 添加 hidden
            ls.className += " hidden";
        } else {
            //包含 删除hidden
            ls.className = ls.className.replaceAll("hidden", "").trim();
        }
    })
}

//功能页面搜索
const checkSearch = () => {
    let searchInput = document.querySelector(".dnfapp-menu .dnfapp-menu-search .search-input");
    searchInput.addEventListener("input", checkSearchListener);

    let searchButton = document.querySelector(".dnfapp-menu .dnfapp-menu-search .search-img");
    searchButton.addEventListener("click", checkSearchListener);
}

const limitStringLength = (text) => {
    if (!text) {
        return "";
    }

    if (text.length <= 5) {
        return text;
    } else {
        return text.substring(0, 4) + "..."
    }
}

const openedTags = [];
let openedTagsIndex = 0; //frame index  每次加1

const menuClick = e => {
    let name = e.getAttribute("name")
    let path = e.getAttribute("path")

    console.log("menuClick", name, path)

    //查找tags是否已经存在
    if (openedTags.indexOf(name) != -1) {
        //直接激活对应标签
        let frames = document.querySelector("#dnf-tags-list").querySelectorAll(".dnfapp-tags");
        let array = [].slice.call(frames)
        array.some(f => {
            if (f.getAttribute("name") == name) {
                tagClick(f);
                return true
            }
        })

        return
    }

    //创建一个新标签
    let index = ++openedTagsIndex;
    let newName = limitStringLength(name);
    let tag = $(`<div class="dnfapp-tags" index="${index}" name="${name}" 
                    onclick="tagClick(this)" oncontextmenu="tagRight(this)">
                    <label>${newName}</label>
                    <div class="dnfapp-tags-close" onclick="tagcloseClick(this)">X</div>
                </div>`
    ).get(0);
    let tagContainer = document.querySelector("#dnf-tags-list")
    tagContainer.appendChild(tag);



    //创建一个新iframe
    let frame = $(`<iframe class="dnfapp-frame-window hidden" src="${path}" index="${index}"></iframe>`).get(0);
    let frameContainer = document.querySelector("#dnf-frame-list");
    frameContainer.appendChild(frame);

    //添加到openedTags
    openedTags.push(name);

    //等待渲染后激活标签
    setTimeout(() => {
        tagClick(tag);

        setTimeout(() => {
            let scroll = $("#dnf-tags-list").getNiceScroll(0)
            scroll.doScrollLeft(100000, 500) //滚动条移动到最右边
        }, 500)
    }, 1);
}

//批量关闭标签
const closeTags = indexs => {
    let tagCtr = document.querySelector("#dnf-tags-list");
    let framCtr = document.querySelector("#dnf-frame-list");

    //删除tag
    GetDocuemtnChildNodes(tagCtr).forEach(element => {
        let elementIndex = element.getAttribute("index");
        if (indexs.indexOf(elementIndex) != -1) {

            //删除openedTags中的name
            let name = element.getAttribute("name");
            let arrIndx = openedTags.indexOf(name);
            if (arrIndx >= 0) {
                openedTags.splice(arrIndx, 1);
            } else {
                console.log("ctxMenuLeft 删除openedTags中的name失败!", index, name);
            }

            //删除tag元素
            tagCtr.removeChild(element);
        }
    });

    //删除frame
    GetDocuemtnChildNodes(framCtr).forEach(element => {
        let elementIndex = element.getAttribute("index");
        if (indexs.indexOf(elementIndex) != -1) {
            framCtr.removeChild(element);
        }
    })
}

//自动激活一个标签
//用于删除标签时
const tagAutoActived = e => {
    //es6有点问题，用jq写吧

    let prev = $(e).prev();//上一个兄弟元素
    // console.log("tagAutoActived prev",prev)
    if (prev.length >= 1) {
        prev.click();
        return;
    }

    let next = $(e).next(); //下一个兄弟元素
    // console.log("tagAutoActived next",next)
    if (next.length >= 1) {
        next.click();
        return;
    }

    //没有其他节点了 创建主页标签
    let index = ++openedTagsIndex;
    let tag = $(`<div class="dnfapp-tags" index="${index}" name="主页" onclick="tagClick(this)" oncontextmenu="tagRight(this)">
                    <label>主页</label>
                    <div class="dnfapp-tags-close" onclick="tagcloseClick(this)">X</div>
                </div>`
    ).get(0);
    let tagContainer = document.querySelector("#dnf-tags-list")
    tagContainer.appendChild(tag);

    //创建一个新iframe
    let frame = $(`<iframe class="dnfapp-frame-window hidden" src="../home/home.html" index="${index}"></iframe>`).get(0);
    let frameContainer = document.querySelector("#dnf-frame-list");
    frameContainer.appendChild(frame);

    //添加到openedTags
    openedTags.push("主页");

    //等待渲染后激活标签
    setTimeout(() => {
        tagClick(tag);
    }, 1);
}

const tagClick = e => {
    console.log("切换标签")
    let tagsGroup = document.querySelector("#dnf-tags-list");
    if (!tagsGroup)
        return

    tagsGroup.querySelectorAll(".dnfapp-tags").forEach(e => {
        e.className = e.className.replace("active", "").trim();
    })
    e.className += " active"

    //切换frame的显示
    let index = e.getAttribute("index");
    let flag = false;
    let frames = document.querySelectorAll(".dnfapp-container .dnfapp-frame-container .dnfapp-frame-window");

    if (!frames) {
        console.log(`切换失败，未找到iframe(index:${index})`);
    }

    //转成数组
    let array = Array.from(frames);
    array.forEach(e => {
        if (e.className.indexOf("hidden") == -1) {
            e.className += " hidden";
        }

        if (e.getAttribute("index") == index) {
            e.className = e.className.replace("hidden", "").trim();
            flag = true;
        }
    })

    if (!flag) {
        console.log(`切换失败，未找到iframe(index:${index})`);
    }
}

let current_tag_right;

const tagRight = e => {
    event.stopPropagation(); //阻止系统右键菜单
    // console.log("标签栏右键了",e)

    //如果不是激活标签则不响应
    // if(e.className.indexOf("active") == -1){
    //     return;
    // }

    current_tag_right = e;
    let ctxMenu = document.querySelector("#tag-contextmenu");
    ctxMenu.className = ctxMenu.className.replaceAll("hidden", "").trim();

    let bounding = e.getBoundingClientRect();
    let left = bounding.left;
    let top = bounding.top;

    let ctxMenuCtr = ctxMenu.querySelector(".dnfapp-tag-contextmenu-container");
    ctxMenuCtr.style.left = (left + 10) + "px";
    ctxMenuCtr.style.top = (top + 20) + "px";

}

const ctxMenuHidden = () => {
    event.stopPropagation();
    let ctxMenu = document.querySelector("#tag-contextmenu");
    ctxMenu.className += " hidden";
    current_tag_right = null;
}

//刷新标签页
const ctxMenuRefresh = () => {
    let index = current_tag_right.getAttribute("index");
    let name = current_tag_right.getAttribute("name");

    let iframeContainer = document.querySelector("#dnf-frame-list");
    let iframes = [].slice.call(iframeContainer.querySelectorAll("iframe")); //子元素 真数组

    if (iframes && iframes.length >= 1) {
        iframes.some(f => {
            if (f.getAttribute("index") == index) {
                f.contentWindow.location.reload(true);
                return true;
            }
        })
    }
}

//关闭标签页
const ctxMenuCurrent = () => {
    let e = current_tag_right.querySelector(".dnfapp-tags-close")
    tagcloseClick(e);
    ctxMenuHidden();
}

//关闭左侧标签页
const ctxMenuLeft = () => {
    tagClick(current_tag_right);

    let prev = $(current_tag_right).prevAll();//前面的兄弟元素

    //遍历出index
    let indexs = []
    $.each(prev, (_, item) => {
        let index = item.getAttribute("index")
        indexs.push(index);
    });

    closeTags(indexs)
    ctxMenuHidden();
}

//关闭右侧标签页
const ctxMenuRight = () => {
    tagClick(current_tag_right);

    let prev = $(current_tag_right).nextAll();//后面的兄弟元素

    //遍历出index
    let indexs = []
    $.each(prev, (_, item) => {
        let index = item.getAttribute("index")
        indexs.push(index);
    });

    closeTags(indexs)
    ctxMenuHidden();
}

//关闭其他标签页
const ctxMenuOther = () => {
    tagClick(current_tag_right);

    let prev = $(current_tag_right).siblings();//同辈元素

    //遍历出index
    let indexs = []
    $.each(prev, (_, item) => {
        let index = item.getAttribute("index")
        indexs.push(index);
    });

    closeTags(indexs)
    ctxMenuHidden();
}

//关闭所有标签页
const ctxMenuAll = () => {
    let indexs = [];
    let tagCtr = document.querySelector("#dnf-tags-list")
    GetDocuemtnChildNodes(tagCtr).forEach(e => {
        indexs.push(e.getAttribute("index"));
    })
    closeTags(indexs)
    ctxMenuHidden();
    tagAutoActived();
}

const tagcloseClick = e => {
    event.stopPropagation(); //阻止父元素响应点击事件

    let index = e.parentNode.getAttribute("index");
    let name = e.parentNode.getAttribute("name");
    console.log("关闭标签", index, name)

    //删除frame
    let iframeContainer = document.querySelector("#dnf-frame-list");
    let iframes = [].slice.call(iframeContainer.querySelectorAll("iframe")); //子元素 真数组

    if (iframes && iframes.length >= 1) {
        iframes.some(f => {
            if (f.getAttribute("index") == index) {
                iframeContainer.removeChild(f);
                return true;
            }
        })
    } else {
        console.log("tagcloseClick  frame未删除!")
    }

    //删除tag
    let tagContainer = document.querySelector("#dnf-tags-list")
    let tags = [].slice.call(tagContainer.querySelectorAll(".dnfapp-tags"));

    if (tags && tags.length >= 1) {
        tags.some(t => {
            if (t.getAttribute("index") == index) {
                tagAutoActived(t); //删除前先激活一个标签
                tagContainer.removeChild(t);
                return true;
            }
        })
    } else {
        console.log("tagcloseClick  tags未删除!")
    }

    //删除openedTags中的记录
    let tagArrayIdx = openedTags.indexOf(name);
    if (tagArrayIdx != -1) {
        openedTags.splice(tagArrayIdx, 1);
    } else {
        console.log("tagcloseClick  openedTags未删除!", openedTags, name, tagArrayIdx)
    }
}

const tagsArrowClick = () => {
    let leftButton = document.querySelector(".dnfapp-container .dnfapp-tags-container .dnfapp-tags-buttons .left")
    if (leftButton) {
        leftButton.addEventListener("click", function () {
            let scroll = $("#dnf-tags-list").getNiceScroll(0)
            scroll.doScrollLeftBy(100)
        });
    }

    let rightButton = document.querySelector(".dnfapp-container .dnfapp-tags-container .dnfapp-tags-buttons .right")
    if (rightButton) {
        rightButton.addEventListener("click", function () {
            let scroll = $("#dnf-tags-list").getNiceScroll(0)
            scroll.doScrollLeftBy(-100)
        });
    }
}

const clearClick = () => {
    let button = document.querySelector("#dnf-console-clear");
    if (button) {
        button.addEventListener("click", function () {
            let textarea = document.querySelector("#dnf-console");
            textarea.value = "";
        })
    }
}

//加载左侧菜单
const loadMenuList = () => {
    //初始化时加载主页
    tagAutoActived();

    sql.menus.queryAll().then(result => {
        console.log("sql.menus.queryAll()", result)

        if (!result)
            return

        const parent = document.querySelector("#dnfapp-menu-list");
        result.forEach(data => {
            if (data.enable == 0)
                return;
            let inner = $(` <div class="menu-list-row" onclick="menuClick(this)"
                                    solt="${data.solt}"
                                    name = "${data.name}"
                                    path="${data.path}" 
                                    enable="${data.enable}">
                                <div class="menu-list-row-img"></div>
                                <div class="menu-list-row-text">${data.name}</div>
                            </div> `
            ).get(0)

            if (data.icon && data.icon != "") {
                const newPath = data.icon.replaceAll("\\", "/"); //**必须用unix路径分隔符
                inner.childNodes.item(1).setAttribute("style", `background-image:url('${newPath}');`)
            } else {
                const base64 = ""
                inner.childNodes.item(1).setAttribute("style", `background-image:url(${base64});`)
            }

            parent.appendChild(inner);
        })
    })

}

//加载自定义设置
//字体颜色
//背景图片
const loadSelfset = () => {
    const body = document.querySelector("body");
    sql.config.queryByName("color").then(result => {
        if (result) {
            body.style.color = result.value
        }
    })

    sql.config.queryByName("backimg").then(result => {
        if (!result) {
            return;
        }
        body.style.background = result.value;
    })

    sql.config.queryByName("tagcolor").then(result => {
        if (!result) {
            return
        }

        if (!window.less || !window.less.modifyVars) {
            return
        }

        window.less.modifyVars({
            "@tagColor": result.value
        })
    });
}


const initScroll = () => {
    $("#dnfapp-menu-list").niceScroll({
        cursorcolor: "gray",
        autohidemode: "cursor",
        smoothscroll: true,
        // boxzoom :true,
        grabcursorenabled: true,
        autohidemode: "scroll",
        railalign: "left",
    });

    $("#dnf-tags-list").niceScroll({
        // cursorcolor:"gray",
        autohidemode: "scroll",
    })
}

const initConsoleChannel = () => {
    electron.ipcRenderOn("console_print", (event, text) => {
        document.print(text);
    })
    electron.ipcRenderOn("console_println", (event, text) => {
        document.println(text);
    })
    electron.ipcRenderOn("console_clear", (event) => {
        document.printclear();
    })
}


window.onload = function () {
    initConsoleChannel();
    loadSelfset();
    checkFold();
    checkSearch();
    clearClick();
    tagsArrowClick();
    loadMenuList();
    initScroll();
}